package com.cnhis.drgs.core.vo;

import freemarker.template.Configuration;
import freemarker.template.Template;
import org.apache.commons.io.IOUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.io.*;
import java.util.Map;

public class FreemarkerHandler {

    private Log logger = LogFactory.getLog(getClass());
    private Configuration cfg;
    private static final String CHARSET = "utf-8";

    public FreemarkerHandler(String pathPrefix) {
        cfg = new Configuration();
        cfg.setClassForTemplateLoading(FreemarkerHandler.class, pathPrefix);
    }

    public Template getTemplate(String name) {
        try {
            return cfg.getTemplate(name, CHARSET);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 输出
     *
     * @param name
     * @param params
     * @param writer
     * @throws Exception
     */
    public void output(String name, Map<String, Object> params, Writer writer) {
        try {
            Template temp = getTemplate(name);
            temp.process(params, writer);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 输出字符串
     *
     * @param name
     * @param params
     */
    public String outputString(String name, Map<String, Object> params) {
        StringWriter sw = null;
        try {
            sw = new StringWriter();
            output(name, params, sw);
            return sw.toString();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            IOUtils.closeQuietly(sw);
        }
        return null;
    }

    /**
     * 输出文件
     *
     * @param name
     * @param params
     * @param outFile
     */
    public void outputFile(String name, Map<String, Object> params, File outFile) {
        PrintWriter pw = null;
        try {
            if (!outFile.getParentFile().exists()) {
                outFile.getParentFile().mkdirs();
            }
            pw = new PrintWriter(new OutputStreamWriter(new FileOutputStream(outFile), CHARSET));
            output(name, params, pw);
            //System.out.println("生成文件(" + outFile.getName() + ") -> " + outFile.getPath());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            IOUtils.closeQuietly(pw);
        }
    }
}
